type eventHandler = (...data: any) => void;
interface Bus {
    emit(eventType: string, data: any): void;
    on(eventType: string, hanlder: eventHandler): void;
    unSubscribe(eventType: string, hanlder: eventHandler): void;
}
class EventBus implements Bus {
    private eventList: { [key: string]: eventHandler[] } = {};

    emit(eventType: string, ...data: any) {// 触发事件
        let hanlderList = this.eventList[eventType]
        if (!hanlderList) return console.log('事件未监听')
        hanlderList.forEach((hanlder) => {
            hanlder.apply(null, data)
        })
    }

    on(eventType: string, hanlder: eventHandler) { // 监听事件
        let hanlderList = this.eventList[eventType]
        if (!hanlderList) {
            this.eventList[eventType] = [hanlder]
        } else {
            hanlderList.push(hanlder)
        }
    }
    unSubscribe(eventType: string, hanlder?: eventHandler) {
        let hanlderList = this.eventList[eventType]
        if (hanlderList && hanlderList.length) {
            if (hanlder) {
                let index = hanlderList.findIndex(hanlder)
                if (index !== -1) {
                    hanlderList.splice(index, 1)
                }
            } else {
                this.eventList[eventType] = []
            }
            console.log(`事件${eventType}已取消监听！`)
        }
    }
}

const eventBus = new EventBus()

export default eventBus